package com.rtx.edi.platform.baseinfo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rtx.api.annotation.RtxDynamicsClass;
import com.rtx.api.annotation.RtxSTDRequest;
import com.rtx.api.enums.DynaicsClassType;
import com.rtx.api.utils.DataTypeUtils;
import com.rtx.common.ClassDescJsonStr;
import com.rtx.common.RtxLoadClass;
import com.rtx.edi.model.apibaseinfo.dto.PlApibaseinfoDTO;
import com.rtx.edi.model.apibaseinfo.po.PlApibaseinfo;
import com.rtx.edi.model.response.EdiResponse;
import com.rtx.edi.platform.baseinfo.service.PlApibaseinfoService;
import com.rtx.wms.std.ctclass.ClassHolder;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * api基础信息表 前端控制器
 * </p>
 *
 * @author zcw
 * @since 2023-03-19
 */
@SuppressWarnings("all")
@Api(tags = {"api基础信息"})
@RestController
@RequestMapping("/v1/edi/apibaseinfo")
public class PlApibaseinfoController {

	@Autowired
	private PlApibaseinfoService PlApibaseinfoService;
	
	@ApiOperation(value = "获取标准报文", notes = "获取标准报文")
	@PostMapping("selectSTDRequest")
	public EdiResponse querySTD(){
		Map<String,List<Map<String,String>>> options = new HashMap<>();
		
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> std = new HashMap<String, String>();
		std.put("lable", "");
		std.put("value", "");
		list.add(std);
		
		List<Map<String,String>> dylist = new ArrayList<Map<String,String>>();
		Map<String,String> dystd = new HashMap<String, String>();
		dystd.put("lable", "");
		dystd.put("value", "");
		dylist.add(dystd);
		
		List<Map<String,String>> dyDetaillist = new ArrayList<Map<String,String>>();
		Map<String,String> dyDetail = new HashMap<String, String>();
		dyDetail.put("lable", "");
		dyDetail.put("value", "");
		dyDetaillist.add(dyDetail);
		
		List<Map<String,String>> allDylist = new ArrayList<Map<String,String>>();
		Map<String,String> allDy = new HashMap<String, String>();
		allDy.put("lable", "");
		allDy.put("value", "");
		allDylist.add(allDy);
		
		Set<Class<?>> set = RtxLoadClass.getClassSet("com.rtx");
		
		for(Class clazz:set) {
			RtxSTDRequest stdRequest = (RtxSTDRequest) clazz.getDeclaredAnnotation(RtxSTDRequest.class);
			if(null != stdRequest) {
				JSONObject root = new JSONObject();

				String json = "";
				if(ClassHolder.supperClassDyJSON.containsKey(clazz.getName())) {
					json = ClassHolder.supperClassDyJSON.get(clazz.getName());
				}else {
					//获取java类对应得json结构
					ClassDescJsonStr.getSTDRequest(clazz,null,root,set);
					json = root.toJSONString();
				}
				
				Map<String,String> s = new HashMap<String, String>();
				s.put("label", stdRequest.name());
				s.put("value", json);
				list.add(s);
			}
			
			//动态类的下拉框
			RtxDynamicsClass dynamicsClass = (RtxDynamicsClass) clazz.getDeclaredAnnotation(RtxDynamicsClass.class);
			if(dynamicsClass != null) {
				
				Map<String,String> alldy = new HashMap<String, String>();
				alldy.put("label", dynamicsClass.name());
				alldy.put("value", clazz.getName());
				allDylist.add(alldy);
				
				if(DynaicsClassType.head.equals(dynamicsClass.type())) {
					Map<String,String> dystd1 = new HashMap<String, String>();
					dystd1.put("label", dynamicsClass.name());
					if(StringUtils.hasLength(dynamicsClass.linkclass())) {
						dystd1.put("value", clazz.getName()+","+dynamicsClass.linkclass());
					}else {
						dystd1.put("value", clazz.getName());
					}
					dylist.add(dystd1);
				}else {
					Map<String,String> dystd2 = new HashMap<String, String>();
					dystd2.put("label", dynamicsClass.name());
					
					if(StringUtils.hasLength(dynamicsClass.linkclass())) {
						dystd2.put("value", clazz.getName()+","+dynamicsClass.linkclass());
					}else {
						dystd2.put("value", clazz.getName());
					}
					
//					dystd2.put("value", clazz.getName());
					dyDetaillist.add(dystd2);
				}
				
			}
			
		}
		
		options.put("stdRequest", list);
		options.put("dynamicsClass", dylist);
		options.put("dynamsubicsClass", dyDetaillist);
		options.put("allDynamsubics", allDylist);
		return EdiResponse.success().data("item", options);
	}
	

	/**
	 * 获取api基础信息列表
	 * @return
	 */
	@ApiOperation(value = "api基础信息列表", notes = "分页获取api基础信息列表")
	@PostMapping("selectPlApibaseinfoList")
	public EdiResponse selectPlApibaseinfoList(@RequestBody(required = false) PlApibaseinfoDTO dto){
		Page<PlApibaseinfo> pageParam = new Page<>(dto.getPageNum(), dto.getPageSize());
		PlApibaseinfo po = new PlApibaseinfo();
		BeanUtils.copyProperties(dto, po);
		PlApibaseinfoService.selectPlApibaseinfoList(pageParam,po);
		return EdiResponse.success().data("page",pageParam);
	}
	
	@ApiOperation(value = "获取api基础信息", notes = "获取api基础信息列表")
	@PostMapping("selectPlApibaseinfo")
	public EdiResponse selectPlApibaseinfo(){
		List<PlApibaseinfo> list = PlApibaseinfoService.selectPlApibaseinfoList();
		List<Map> item = new ArrayList<>();
		for(PlApibaseinfo info:list) {
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("id", info.getId());
			map.put("companyId", info.getCompanyId());
			map.put("applicationId", info.getApplicationId());
			item.add(map);
		}
		return EdiResponse.success().data("item",item);
	}

	/**
	 * 根据ID获取api基础信息
	 * @param PlApibaseinfo
	 * @return
	 */
	@ApiOperation(value = "查询api基础信息", notes = "根据ID查询api基础信息")
	@PostMapping("selectPlApibaseinfoById")
	public EdiResponse selectPlApibaseinfoById(@RequestBody PlApibaseinfo dto){
		return EdiResponse.success().data("item",PlApibaseinfoService.getById(dto.getId()));
	}
	/**
	 * 根据id删除
	 * @param PlApibaseinfo
	 * @return
	 */
	@ApiOperation(value = "删除api基础信息", notes = "根据id删除api基础信息", httpMethod = "POST")
	@PostMapping("deletePlApibaseinfoById")
	public EdiResponse deletePlApibaseinfoById(@RequestBody PlApibaseinfo dto) {
		return PlApibaseinfoService.removeById(dto.getId()) ? EdiResponse.success() : EdiResponse.failed();
	}
	
	/**
	 * 根据id删除
	 * @param PlApibaseinfo
	 * @return
	 */
	@ApiOperation(value = "删除api基础信息集合", notes = "删除api基础信息集合", httpMethod = "POST")
	@PostMapping("deletePlApibaseinfoByIds")
	public EdiResponse deletePlApibaseinfoByIds(@RequestBody List<PlApibaseinfo> list) {
        List<Long> ids = list.stream().map(p -> p.getId()).distinct().collect(Collectors.toList());
		return PlApibaseinfoService.removeBatchByIds(ids) ? EdiResponse.success() : EdiResponse.failed();
	}
	
	/**
	 * 新增api基础信息
	 * @param PlApibaseinfo
	 * @return
	 */
	@ApiOperation(value = "新增api基础信息")
	@PostMapping("addPlApibaseinfo")
	public EdiResponse addPlApibaseinfo(@RequestBody PlApibaseinfoDTO dto){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String companyid = (String) Optional.ofNullable(session.getAttribute("companyid")).orElse("1");
		
        LambdaQueryWrapper<PlApibaseinfo> qw = Wrappers.lambdaQuery();
        qw.eq(PlApibaseinfo::getApiName, dto.getApiName())
        .eq(PlApibaseinfo::getApplicationId, dto.getApplicationId());
        boolean  exists = PlApibaseinfoService.getBaseMapper().exists(qw);
        if(exists) {
        	return EdiResponse.failed().returnMgr("api名称已经存在不允许重复创建！");
        }
        
        PlApibaseinfo po = new PlApibaseinfo();
		BeanUtils.copyProperties(dto, po);
		
		po.setApiRequestTemplate(DataTypeUtils.resolveDataTypeAndConvertToJsonStr(po.getApiRequestTemplate()));
		
		po.setCompanyId(companyid);
		return PlApibaseinfoService.save(po)  ? EdiResponse.success() : EdiResponse.failed();
	}

	/**
	 * 根据ID修改api基础信息
	 * @return
	 */
	@ApiOperation(value = "修改api基础信息", notes = "根据ID修改api基础信息")
	@PostMapping("editPlApibaseinfoById")
	public EdiResponse editPlApibaseinfoById(@RequestBody PlApibaseinfoDTO dto){
		PlApibaseinfo po = new PlApibaseinfo();
		BeanUtils.copyProperties(dto, po);
		po.setApiRequestTemplate(DataTypeUtils.resolveDataTypeAndConvertToJsonStr(po.getApiRequestTemplate()));
		return PlApibaseinfoService.updateById(po) ? EdiResponse.success() : EdiResponse.failed();
	}
	
	public EdiResponse compareTableField(@RequestBody PlApibaseinfoDTO dto) {
		return null;
	}
}
